﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>货品类型</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        /* 页面整体背景 */
        body {
            background-color: #f0f2f5;
            margin: 0;
            padding: 0;
            font-family: "PingFang SC", "Microsoft Yahei", sans-serif;
        }

        .container {
            width: 1200px;
            margin-left: 20px;
            margin-top: 20px;
            background-color: #fff;
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            padding: 24px;
        }

        .search-area {
            margin-bottom: 16px;
            padding: 16px;
            background-color: #f5f7fa;
            border-radius: 4px;
            display: flex;
            align-items: center;
            gap: 16px;
        }

        /* 自定义class：状态下拉框宽度 */
        .searchForm-status {
            width: 90px;
        }

        /* 自定义class：操作时间选择器宽度 */
        .searchForm-time {
            width: 200px !important;
        }

        .searchForm-operator{
            width: 120px;
        }

        .btn-group {
            margin-bottom: 16px;
            display: flex;
            gap: 8px;
        }

        .table-container {
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            overflow: hidden;
        }

        .fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }

        @@keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        /* 表头样式：灰色背景 + 加粗文字 */
        .el-table__header th {
            background-color: #f0f2f5 !important;
        }

        .el-table__header .el-table__header-cell .cell {
            font-weight: bold !important;
        }
    </style>
</head>
<body>
    <!-- 应用容器 -->
    <div id="goods-type-app" class="container fade-in">
        <!-- 搜索区域 HTML 修改 -->
        <div class="search-area">
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="货品类型">
                    <el-input v-model="searchForm.goodsType" class="searchForm-goodsType" placeholder="货品类型名称/编号"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <!-- 给状态下拉框添加自定义class -->
                    <el-select v-model="searchForm.status" class="searchForm-status" placeholder="请选择">
                        <el-option label="启用" value="启用"></el-option>
                        <el-option label="停用" value="停用"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="操作人">
                    <el-input v-model="searchForm.operator" placeholder="请输入" class="searchForm-operator"></el-input>
                </el-form-item>
                <el-form-item label="操作时间">
                    <!-- 给时间选择器添加自定义class -->
                    <el-date-picker v-model="searchForm.operateTime"
                                    class="searchForm-time"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    placeholder="请选择时间范围" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="handleSearch">查询</el-button>
                    <el-button v-on:click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 功能按钮区域 -->
        <div class="btn-group">
            <el-button type="primary" v-on:click="handleAdd">新增</el-button>
            <el-button v-on:click="handleImport">导入</el-button>
            <el-button v-on:click="handleExport">导出</el-button>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-container">
            <el-table :data="tableData" style="width: 100%">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="product_type_code" label="货品类型编号" width="120"></el-table-column>
                <!-- 货品类型名称：带层级缩进 -->
                <el-table-column label="货品类型名称" width="120">
                    <template #default="scope">
                        <div :style="{ 'padding-left': `${scope.row.level * 20}px` }">
                            {{ scope.row.product_type_name }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="sorting" label="排序" width="80"></el-table-column>
                <el-table-column label="状态" width="80">
                    <template #default="scope">
                        {{ scope.row.status === 1 ? '启用' : '停用' }}
                    </template>
                </el-table-column>
                <el-table-column prop="note" label="备注" width="200"></el-table-column>
                <el-table-column prop="create_by" label="操作人" width="100"></el-table-column>
                <el-table-column prop="create_time" label="操作时间" width="200">
                    <template #default="scope">
                        {{ scope.row.create_time.replace('T', ' ') }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" v-on:click="handleEdit(scope.row)">编辑</el-button>
                        <el-button link type="danger" size="small" v-on:click="handleDeleteRow(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>




        <!-- 新增货品类型模态框 -->
        <el-dialog v-model="dialogVisible" title="新增货品类型" width="50%">
            <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
                <!-- 上级分类 -->
                <el-form-item label="上级分类" prop="parentId">
                    <el-select v-model="formData.parentId" placeholder="请选择" clearable>
                        <el-option v-for="item in selectOptions"
                                   :key="item.product_type_id"
                                   :label="item.product_type_name"
                                   :value="item.product_type_id"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 货品类型编号（自动生成，可禁用输入） -->
                <el-form-item label="货品类型编号" prop="product_type_code">
                    <el-input v-model="formData.product_type_code" placeholder="自动获取系统编号" disabled></el-input>
                </el-form-item>
                <!-- 货品类型名称（必填） -->
                <el-form-item label="货品类型名称" prop="product_type_name">
                    <el-input v-model="formData.product_type_name" placeholder="请输入"></el-input>
                </el-form-item>
                <!-- 排序（数字类型） -->
                <el-form-item label="排序" prop="sorting">
                    <el-input v-model.number="formData.sorting" placeholder="请输入"></el-input>
                </el-form-item>
                <!-- 状态（启用/停用） -->
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="formData.status">
                        <el-radio label="1">启用</el-radio>
                        <el-radio label="2">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 备注（多行文本） -->
                <el-form-item label="备注" prop="note">
                    <el-input v-model="formData.note" type="textarea" rows="4" placeholder="请输入"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click ="dialogVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click ="handleSubmit">保存</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 编辑货品类型模态框 -->
        <el-dialog v-model="editDialogVisible" title="编辑货品类型" width="50%">
            <el-form :model="editFormData" :rules="editRules" ref="editFormRef" label-width="120px">
                <el-form-item label="货品类型编号" prop="product_type_code">
                    <el-input v-model="editFormData.product_type_code" placeholder="货品类型编号" disabled></el-input>
                </el-form-item>
                <!-- 上级分类 -->
                <el-form-item label="上级分类" prop="parent_category_id">
                    <el-select v-model="editFormData.parent_category_id" placeholder="请选择" clearable>
                        <el-option v-for="item in selectOptions"
                                   :key="item.product_type_id"
                                   :label="item.product_type_name"
                                   :value="item.product_type_id.toString()"></el-option>
                    </el-select>
                </el-form-item>
                <!-- 货品类型名称（必填） -->
                <el-form-item label="货品类型名称" prop="product_type_name">
                    <el-input v-model="editFormData.product_type_name" placeholder="请输入"></el-input>
                </el-form-item>
                <!-- 排序（数字类型） -->
                <el-form-item label="排序" prop="sorting">
                    <el-input v-model.number="editFormData.sorting" placeholder="请输入"></el-input>
                </el-form-item>
                <!-- 状态（启用/停用） -->
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="editFormData.status">
                        <!-- 将label改为数字类型绑定 -->
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="2">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 备注（多行文本） -->
                <el-form-item label="备注" prop="note">
                    <el-input v-model="editFormData.note" type="textarea" rows="4" placeholder="请输入"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click="handleUpdate">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>


    <!-- 引入 Vue 和 Element Plus JS -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <script>
        const { createApp, ref, reactive, onMounted, nextTick } = Vue;
        const app = createApp({
            setup() {
                const searchForm = reactive({
                    goodsType: '',
                    status: '',
                    operator: '',
                    operateTime: [] // 时间范围数组 [开始时间, 结束时间]
                });

                const tableData = ref([]);

                // 树形数据转平级（带层级）
                const flattenTree = (treeData, level = 0) => {
                    let result = [];
                    treeData.forEach(node => {
                        result.push({ ...node, level });
                        if (node.children && node.children.length > 0) {
                            result = result.concat(flattenTree(node.children, level + 1));
                        }
                    });
                    console.log(result);
                    return result;
                };

                // 加载数据（支持带查询参数）
                const loadTreeData = async (params = {}) => {
                    let url = '/GoodsType/GetGoodsTypeTree';
                    if (Object.keys(params).length > 0) {
                        url += '?';
                        const queryParams = Object.entries(params).map(([key, value]) => {
                            if (key === 'operateTime' && Array.isArray(value) && value.length === 2) {
                                return `startTime=${value[0]}&endTime=${value[1]}`;
                            }
                            return `${key}=${encodeURIComponent(value)}`;
                        }).join('&');
                        url += queryParams;
                    }
                    const response = await fetch(url);
                    const treeData = await response.json();
                    
                    tableData.value = flattenTree(treeData);
                    console.log(tableData.value);
                    await nextTick();
                };

                onMounted(() => {
                    loadTreeData(); // 页面加载时加载全部数据
                });

                // 搜索功能：传递查询参数
                const handleSearch = () => {
                    const params = {
                        goodsType: searchForm.goodsType,
                        status: searchForm.status,
                        operator: searchForm.operator,
                        operateTime: searchForm.operateTime
                    };
                    loadTreeData(params);
                };

                // 重置功能：清空条件并加载全部数据
                const handleReset = () => {
                    searchForm.goodsType = '';
                    searchForm.status = '';
                    searchForm.operator = '';
                    searchForm.operateTime = [];
                    loadTreeData();
                };

                //=================模态框添加部分=========================

                // 模态框默认关闭（只保留这一次声明）
                const dialogVisible = ref(false);

                //新增按钮的点击事件
                const handleAdd = () => {
                    // 1. 先获取上级分类选项（带层级）
                    getParentTypeOptions().then(() => {
                        // 2. 再打开模态框
                        dialogVisible.value = true;
                        // 3. 最后获取货品类型编号
                        getGoodsTypeNumber();
                    });
                };
                const handleImport = () => console.log('导入操作');
                const handleExport = () => console.log('导出操作');


                // 模态框表单相关逻辑
                const formRef = ref(null); // 表单引用，用于验证和重置

                //初始化
                const selectOptions = ref([]);

                const formData = reactive({
                  parentId: 0, // 上级分类ID，默认“无上级”
                  product_type_code: '', //货品类型编号
                  product_type_name: '', // 货品类型名称（必填）
                  sorting: 0, // 排序（数字类型）
                  status: '1', // 状态：1启用，2停用
                  note: '' // 备注
                });



                const getParentTypeOptions = async () => {
                    try {
                        // 调用后端新增的 GetParentTypeOptions 接口
                        const response = await axios.get("/GoodsType/GetParentTypeOptions");
                        // 将后端返回的带层级选项数据赋值给 selectOptions
                        selectOptions.value = response.data;
                        console.log("上级分类选项（带层级）：", selectOptions.value);
                    } catch (err) {
                        console.error("获取上级分类选项失败：", err);
                        ElementPlus.ElMessage.error("获取上级分类失败，请稍后再试");
                    }
                };



            
            const getGoodsTypeNumber = async () => {
                try {
                    // 1. 封装请求体：将rule_id放在Body中，与后端[FromBody]匹配
                    const requestData = {
                        rule_id: 22 // 货品类型对应的规则ID
                    };

                    // 2. 发送POST请求：明确设置Content-Type为JSON，确保后端正确解析
                    const res = await axios.post(
                        "/NumberingRule/GenerateBusinessNumber", // 移除URL后的?rule_id=22
                        requestData, // 请求体数据（核心修改点）
                        {
                            headers: {
                                "Content-Type": "application/json" // 明确JSON格式
                            }
                        }
                    );

                    if (res.data.success) {
                        formData.product_type_code = res.data.businessNumber;
                        console.log("获取的货品类型编号：", formData.product_type_code);
                        ElementPlus.ElMessage.closeAll(); // 关闭错误提示
                    } else {
                        ElementPlus.ElMessage.error(res.data.message || "生成货品类型编号失败");
                    }

                } catch (err) {
                    console.error("获取货品类型编号失败：", err);
                    ElementPlus.ElMessage.error("网络异常，获取货品类型编号失败，请稍后再试");
                }
            };


                // 表单验证规则
                const rules = reactive({
                  product_type_name: [
                    { required: true, message: '请输入货品类型名称', trigger: 'blur' }
                  ],
                  sorting: [
                    { required: true, message: '请输入排序', trigger: 'blur' },
                    { type: 'number', message: '排序必须为数字', trigger: 'blur' }
                  ],
                  parentId: [
                    { required: true, message: '请选择上级分类', trigger: 'change' }
                  ],
                  status: [
                    { required: true, message: '请选择状态', trigger: 'change' }
                  ]
                });

                // 提交表单（含验证逻辑）
                const handleSubmit = () => {
                    formRef.value.validate((valid) => {
                        if (valid) {
                            // 构造与后端 AddWMSBasicTypeOfGoods 模型完全匹配的 JSON 参数
                            const submitData = {
                                parent_category_id: formData.parentId.toString(), // 后端是 string 类型
                                product_type_code: formData.product_type_code,
                                product_type_name: formData.product_type_name,
                                sorting: formData.sorting, // 后端是 int 类型，前端直接传数字
                                note: formData.note,
                                status: formData.status === '1' ? 1 : 2 // 后端是 int 类型，0=启用，1=停用
                            };

                            // 显式指定请求头为 JSON 格式
                            axios.post("/GoodsType/AddTypes", submitData, {
                                headers: {
                                    'Content-Type': 'application/json'
                                }
                            })
                            .then(response => {
                                const res = response.data;
                                if (res.success) {
                                    ElementPlus.ElMessage.success(res.message || "添加成功");
                                    dialogVisible.value = false;
                                    formRef.value.resetFields();
                                    handleSearch();
                                } else {
                                    ElementPlus.ElMessage.error(res.message || "添加失败");
                                }
                            })
                            .catch(err => {
                                console.error("添加货品类型失败：", err);
                                ElementPlus.ElMessage.error("网络错误，添加失败");
                            });
                        }
                    });
                };

                // 编辑弹窗相关变量
                const editDialogVisible = ref(false);
                const editFormRef = ref(null);
                const editFormData = reactive({
                  product_type_id: null,
                  parent_category_id: '',
                  product_type_code: '',
                  product_type_name: '',
                  sorting: 0,
                  note: '',
                  status: 1,
                });

                const editRules = reactive({
                    product_type_name: [
                      { required: true, message: '请输入货品类型名称', trigger: 'blur' }
                    ],
                    sorting: [
                      { required: true, message: '请输入排序', trigger: 'blur' },
                      { type: 'number', message: '排序必须为数字', trigger: 'blur' }
                    ],
                    parent_category_id: [ // 字段名改为parent_category_id
                      { required: true, message: '请选择上级分类', trigger: 'change' }
                    ],
                    status: [
                      { required: true, message: '请选择状态', trigger: 'change' }
                    ]
                });

                // 点击“编辑”按钮时，获取详情并回显
                const handleEdit = async (row) => {
                  await getParentTypeOptions(); // 加载上级分类选项
                  // 调用后端查询接口，获取货品类型详情
                  const res = await axios.get(`/GoodsType/GetType?product_type_code=${row.product_type_code}`);
                  if (res.data.success) {
                    const data = res.data.data;
                    // 填充编辑表单
                    editFormData.product_type_id = data.product_type_id;
                    editFormData.parent_category_id = data.parent_category_id.toString();
                    editFormData.product_type_code = data.product_type_code;
                    editFormData.product_type_name = data.product_type_name;
                    editFormData.sorting = data.sorting;
                    editFormData.note = data.note;
                    editFormData.status = data.status;
                    console.log(editFormData)
                    editDialogVisible.value = true; // 打开编辑弹窗
                  } else {
                    ElementPlus.ElMessage.error(res.data.message || "查询失败");
                  }
                };

                // 提交编辑表单，调用后端更新接口
                const handleUpdate = () => {
                  editFormRef.value.validate((valid) => {
                    if (valid) {
                      const submitData = {
                        product_type_id: editFormData.product_type_id,
                        parent_category_id: editFormData.parent_category_id,
                        product_type_code: editFormData.product_type_code,
                        product_type_name: editFormData.product_type_name,
                        sorting: editFormData.sorting,
                        note: editFormData.note,
                        status: editFormData.status,
                        update_by: 'admin', // 实际项目中替换为当前登录用户名
                        update_time: new Date()
                      };
                      console.log(submitData)
                      console.log("submitData")
                      axios.post("/GoodsType/UpdateType", submitData, {
                        headers: { 'Content-Type': 'application/json' }
                      })
                      .then(response => {
                        if (response.data.success) {
                          ElementPlus.ElMessage.success(response.data.message || "修改成功");
                          editDialogVisible.value = false;
                          editFormRef.value.resetFields();
                          handleSearch(); // 刷新表格
                        } else {
                          ElementPlus.ElMessage.error(response.data.message || "修改失败");
                        }
                      })
                      .catch(err => {
                        console.error("修改失败：", err);
                        ElementPlus.ElMessage.error("网络错误，修改失败");
                      });
                    }
                  });
                };

                // 点击“删除”按钮时，弹出确认框并调用删除接口
                const handleDeleteRow = (row) => {
                    ElementPlus.ElMessageBox.confirm(
                        '确认删除该货品类型吗？删除后不可恢复',
                        '提示',
                        { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }
                    )
                    .then(async () => {
                        const res = await axios.post("/GoodsType/DeleteType",null,{params: { product_type_code: row.product_type_code }});
                        // 调用后端删除接口
                        //     const response = await axios.post("/Supplier/Delete", null, {
                        //         params: { supplier_code: row.code } 传递供应商编码
                        //     });
                        if (res.data.success) {
                            ElementPlus.ElMessage.success(res.data.message || "删除成功");
                            handleSearch(); // 刷新表格
                        } else {
                            ElementPlus.ElMessage.error(res.data.message || "删除失败");
                        }
                    })
                    .catch(() => {
                        ElementPlus.ElMessage.info("已取消删除");
                    });
                };

                      
                return {
                    searchForm,
                    tableData,
                    handleSearch,
                    handleReset,
                    handleAdd,
                    handleImport,
                    handleExport,
                    handleEdit,
                    handleDeleteRow,
                    dialogVisible,
                    formRef,
                    selectOptions,
                    formData,
                    rules,
                    handleSubmit,
                    editDialogVisible,
                    editFormRef,
                    editFormData,
                    handleUpdate,
                    editRules,
                    handleDeleteRow,
                };
            }
        });
        app.use(ElementPlus);
        app.mount('#goods-type-app');
    </script>
</body>
</html>